import { Button, LoadPanel, Popup, SelectBox, TagBox } from 'devextreme-react';
import { IColumnProps, Item, Paging, Toolbar } from 'devextreme-react/data-grid';
import React, {
  ReactNode,
  useCallback,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from 'react';
import { DevGrid, LayoutB } from '~/public/cpas-ui';

import AccountingVoucherPupop from '@/pages/accountingEntryTest/rightTables/components/accountingVoucherPupop';
import getApiData from '@/services/cpasRequest';
import { msgError, msgInfo } from '@/utils/msg';
import {
  formatDateYYMMDD,
  getGridDefaultPageProps,
  setDevOptions,
  tabBoxOnMultiTagPreparingOfProp,
} from '@/utils/pub';
import { QuestionCircleTwoTone } from '@ant-design/icons';
import { Modal } from 'antd';
import { LoadOptions } from 'devextreme/data';
import CustomStore from 'devextreme/data/custom_store';
import { EditingStartEvent } from 'devextreme/ui/data_grid';
import ReactDOM from 'react-dom';
import { useModel } from 'umi';
import { consts } from '../consts';
import { getNotExistsColumns } from '../tableColumnData';
import { AccountInfo, ExcelTable, SampleField, SampleTable } from '../typing';
import './index.less';
import { ImportExcelPupop } from './samplingImportExcelPopup';
import { udpateRowsDataRnValue } from './samplingProjectOverallService';
import { getSampleTableList } from './samplingRecordPopupService';
import {
  alterTableFieldType,
  getDataGridLoadSortFields,
  getFieldValuesIsNumber,
  getSampledTables,
  getSampleSourceColums,
  getSampleSourceFieldValues,
  getTableFieldValueMaxLen,
  getTextFieldValueIsKeyOfMsg,
  getWhereSqlByFilterAnd,
  loadSampleSourceDataListOnly,
  udpateSampleTableFieldInfo,
  udpateSampleTableValue,
  updateSampleTableProps,
} from './samplingSourceService';
import {
  devPopupTitleRendered,
  getAccountInfoList,
  getPageInfoByLoadOptions,
  getRealTableName_sampleList,
  getSortFiedsCantSort,
} from './service';
import { SortFieldsPopup } from './sortFieldsPopup';
import { inputQuery } from './tools/dialogs';

/**
 * 样本源维护
 */

export const SamplingSourcePopup = React.forwardRef((props: any, ref: any) => {
  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd } = initialState?.curPart as any;
  const [visible, setVisible] = useState<boolean>(false);
  //样本源的表
  const [sampleTableList, setSampleTableList] = useState<SampleTable[]>([]);
  //样本源的数据
  const [sampleSourceTableDataSource, setSampleSourceTableDataSource] = useState<
    CustomStore | any[]
  >();
  const [sampleSourceDataColumns, setSampleSourceDataColumns] = useState<IColumnProps[]>([]);
  const [sampleSourceFields, setSampleSourceFields] = useState<SampleField[]>([]);
  const [curSampleSourceField, setCurSampleSourceField] = useState<SampleField>();
  const popupRef = useRef<any>();
  const devGridSampleTableRef = useRef<any>();
  const devGridSampleSourceRef = useRef<any>();
  const sortFieldsPopupRef = useRef<any>();
  const importExcelPopupRef = useRef<any>();
  const [isNeedSortFieldsPopup, setIsNeedSortFieldsPopup] = useState<boolean>(false);
  const [isNeedImportExcelPopup, setIsNeedImportExcelPopup] = useState<boolean>(false);
  const [isNeedAccountingVouche, setIsNeedAccountingVouche] = useState<boolean>(false);

  const accountingVoucherPupopRef = useRef<any>(null);
  /*   const [pageIndex, setPageIndex] = useState<number>(0);
      const [pageSize, setPageSize] = useState<number>(consts.defaultSampePageSize); */
  // const curSampleTable = useRef<SampleTable>();

  const [loading, setLoading] = useState<boolean>(false);

  const [curSampleTable, setCurSampleTable] = useState<SampleTable>();
  const [accountInfoList, setAccountInfoList] = useState<AccountInfo[]>([]);

  const [curDataId, setCurDataId] = useState<string>('');

  const diaParams = useRef<any>(null);

  /**
   * 获取样本表
   * @returns
   */
  const loadSampleSourceDataList = useCallback(
    async (sampleTable?: SampleTable, sampleSourceFields?: SampleField[], dataId?: string) => {
      if (!sampleTable?.tableName) return [];
      //setLoading(true) 不能加,会导致多次请求loadSampleSourceDataListOnly
      setSampleSourceTableDataSource(
        new CustomStore({
          key: 'rn',
          load: async (loadOptions: LoadOptions) => {
            let rowsData: any[] = [];
            const { pageIndex, pageSize } = getPageInfoByLoadOptions(loadOptions);

            let filterWhereSql = getWhereSqlByFilterAnd(loadOptions.filter);
            console.log('loadOptions.filter', loadOptions.filter);
            console.log('whereSql', filterWhereSql);
            const dataField = (loadOptions as any).dataField;
            //点击表头的过滤器时,只查询
            if (dataField) {
              rowsData = await getSampleSourceFieldValues(
                dbname,
                sampleTable,
                dataField,
                dataId,
                filterWhereSql,
              );
            } else {
              //正常查询数据时
              const sortFields = getDataGridLoadSortFields(loadOptions);
              if (getSortFiedsCantSort(sortFields)) {
                msgError('此列不能排序!');
                devGridSampleSourceRef.current.instance.clearSorting();
                rowsData = devGridSampleSourceRef.current.instance.getDataSource()._items; //取原来的数据行
              } else {
                rowsData = await loadSampleSourceDataListOnly(
                  dbname,
                  sampleTable,
                  pageIndex,
                  pageSize,
                  sampleSourceFields,
                  sortFields,
                  dataId,
                  filterWhereSql,
                );
              }
            }
            return {
              data: rowsData,
              totalCount: rowsData.length ? rowsData[0].tc : 0,
            };
          },
        }),
      );
      return [];
      //return rowsData;
    },
    [curSampleTable, sampleSourceFields, curDataId],
  );
  const onCancel = () => {
    diaParams.current?.setIsNeedSamplingSourcePopup &&
      diaParams.current.setIsNeedSamplingSourcePopup(false);
    // setSampleSourceTableDataSource([] as any)
    //失败devGridSampleTable的所有数据
    let element = document.getElementById('leftContainer');
    element && ReactDOM.unmountComponentAtNode(element);
    element = document.getElementById('rightContainer');
    element && ReactDOM.unmountComponentAtNode(element);
    //关闭时回传数据
    diaParams.current?.updateSampleTableList &&
      diaParams.current.updateSampleTableList(sampleTableList);
    setVisible(false);
  };

  /**
   * 加载样本表
   * @param accountInfoList
   * @param dataId
   */
  function loadSampleTableList(dataId: string) {
    getSampleTableList(dbname, dataId, setSampleTableList).then(async (sampleTableList) => {
      if (sampleTableList.length) {
        setDevOptions(devGridSampleTableRef, { focusedRowKey: sampleTableList[0].guid });
        setCurSampleTable(sampleTableList[0]);
        loadSampleSourceInfo(sampleTableList[0], dataId);
      }
    });
  }
  // 自定义方法
  useImperativeHandle(ref, () => ({
    show: (params: any) => {
      diaParams.current = params;

      setVisible(true);

      setTimeout(async () => {
        const accountInfoList = await getAccountInfoList({ dbname });
        let dataId: string = '';
        if (accountInfoList.length) {
          dataId = accountInfoList[accountInfoList.length - 1].Data_ID;
          setCurDataId(dataId);
        }
        setAccountInfoList(accountInfoList);
        loadSampleTableList(dataId);
      }, 800);
    },
  }));

  //删除
  const onDelClickOfTable = async (e: any) => {
    let sampleTableList: SampleTable[] =
      devGridSampleTableRef.current.instance.getSelectedRowsData();
    sampleTableList = sampleTableList.filter((item) => item.isCustom);
    if (sampleTableList.length == 0) {
      return msgError('请选择要删除的表(系统表不能删除)!');
    }

    let sysTablesList: SampleTable[] = sampleTableList.filter((item) => !item.isCustom);
    //如果只选择了系统表,就提示,全选时,是可以删除非自定义的
    if (sysTablesList.length == sampleTableList.length) {
      const tableTitles = sysTablesList.map((item) => item.tableTitle).join('、');
      return msgError(`系统定义的表名【${tableTitles}】不能删除, 请不要选择此表!`);
    }

    const sampledTableNames = await getSampledTables(
      dbname,
      sampleTableList.map((item) => item.tableName),
    );

    if (sampledTableNames.length > 0) {
      let sampledTableTitles = sampleTableList
        .filter((item) => sampledTableNames.includes(item.tableName))
        .map((item) => item.tableTitle)
        .join('、');
      return msgError(`表【${sampledTableTitles}】已进行抽样不能删除,请先删除抽样记录!`);
    }

    const promptName = `【${sampleTableList[0].tableTitle}】等 ${sampleTableList.length} 个表`;
    //执行删除
    async function batDelSampleTableList() {
      for (const sampleTable of sampleTableList) {
        const retData = await getApiData('sample.delSampleTable', {
          dbname,
          tableName: sampleTable.tableName,
          allSampleRecordTable: getRealTableName_sampleList(sampleTable.tableName, {
            data_id: curDataId,
          }),
        });
        if (!retData.ok) {
          msgError(`【${sampleTable.tableTitle}】删除椒: ${retData.data}`);
          return false;
        }
      }
      return true;
    }

    Modal.confirm({
      zIndex: 5000,
      content: `确定要删除${promptName}吗？`,
      onOk: async () => {
        setLoading(true);
        await batDelSampleTableList();
        setLoading(false);
        //重新加载最后一个
        const sampleTableList = await getSampleTableList(dbname, curDataId, setSampleTableList);
        if (sampleTableList.length) {
          const newSampleTale: SampleTable = sampleTableList[sampleTableList.length - 1];
          setCurSampleTable(newSampleTale);
          loadSampleSourceInfo(newSampleTale, curDataId);
          setSampleSourceTableDataSource([]);
        }
      },
    });
  };

  //编辑
  const onEditClickOfTable = (e: any) => {
    if (!curSampleTable) {
      return msgError('还没有表名,请选择一个!');
    }
    const sampleTale: SampleTable = curSampleTable;
    if (!sampleTale.isCustom) {
      return msgError('系统定义的表名,不能修改!');
    }
    //   console.log('onEditClickOfTable', sampleTale);

    inputQuery(
      '',
      '',
      curSampleTable.tableTitle,
      async (value: string) => {
        if (value == curSampleTable.tableTitle) {
          msgError('【' + value + '】 名称未修改!');
          return false;
        }

        if (sampleTableList.some((item) => item.tableTitle == value)) {
          msgError('【' + value + '】名称重复!');
          return false;
        }

        devGridSampleTableRef.current.instance.cellValue(
          curSampleTable.rn - 1,
          'tableTitle',
          value,
        );
        devGridSampleTableRef.current.instance.saveEditData();
        udpateSampleTableValue(sampleTableList, curSampleTable, dbname, 'tableTitle', value);

        return true;
      },
      '',
      { zIndex: 2000 },
    );
  };
  //加载样本源信息
  async function loadSampleSourceInfo(sampleTable: SampleTable, dataId: string) {
    try {
      //  setLoading(true)
      const sampleSourceFields = sampleTable.sampleAllFieldsArray; // await getSampleSourceFields(dbname, sampleTable.tableName);

      let columns = getSampleSourceColums(
        sampleSourceFields.filter((item) => item.visible),
        true,
        true,
      );
      const existsColumns = sampleSourceFields.length > 0;
      columns = existsColumns ? columns : getNotExistsColumns(sampleTable.tableTitle);

      /*setDevOptions(devGriSampleSourceRef, {columns}) */

      setSampleSourceFields(sampleSourceFields);

      setSampleSourceDataColumns(columns);
      //

      if (existsColumns) {
        loadSampleSourceDataList(sampleTable, sampleSourceFields, dataId);
      } else {
        setSampleSourceTableDataSource([] as any);
      }

      //  setLoading(false)
    } catch (error) {}
  }
  /**
   * 排序字段
   * @param sampleTable
   */
  function showSortFieldsPopup(sampleTable: SampleTable | undefined) {
    setIsNeedSortFieldsPopup(true);

    const interval = setInterval(() => {
      if (sortFieldsPopupRef?.current) {
        clearInterval(interval);
        sortFieldsPopupRef.current.show({
          title: '拖拽字段进行排序  ',
          sampleTable,
          sampleSourceFields,
          onOk: (sortFields: string[]) => {
            if (sampleTable) {
              sampleTable.sortFields = sortFields.join(',');
              sampleTable.sortFieldsArray = sortFields;
              udpateSampleTableValue(
                sampleTableList,
                sampleTable,
                dbname,
                'sortFields',
                sortFields.join(','),
              );
              setIsNeedSortFieldsPopup(false);
              loadSampleSourceDataList(sampleTable, sampleSourceFields, curDataId);
            }
          },
        });
      }
    }, 10);
  }

  /**
   * 从Excel导入
   */
  const showImportExcelPopup = async () => {
    const fileInfo: { filePaths: string[]; canceled: boolean } =
      await window.electronComponents.openDialog({
        properties: ['openFile'],
        title: '请选择Excel文件',
        filters: [{ name: 'Excel文件', extensions: ['xlsx'] }],
      });
    if (!fileInfo.canceled) {
      const fileOrUrl = fileInfo.filePaths[0];

      setIsNeedImportExcelPopup(true);
      const interval = setInterval(() => {
        if (importExcelPopupRef?.current) {
          clearInterval(interval);
          importExcelPopupRef.current.show({
            title: '导入Excel表',
            dataId: curDataId,
            accountInfoList: accountInfoList,
            excelFilePath: fileOrUrl,
            maxOrdexIndex: sampleTableList.reduce((max, item) => Math.max(max, item.orderIndex), 0),
            sampleTableList,
            onCancel: () => {
              setIsNeedImportExcelPopup(false);
            },
            onOk: async (newExcelTableList: ExcelTable[]) => {
              setIsNeedImportExcelPopup(false);
              const index = sampleTableList?.length || 0; //老的个数,新加的要选择最后一个
              let newSampleTableList = await getSampleTableList(
                dbname,
                curDataId,
                setSampleTableList,
              );
              const newCurSampleTable = newSampleTableList.find(
                (item) => item.tableName == newExcelTableList[0].tableName,
              );
              if (newCurSampleTable) {
                setCurSampleTable(newCurSampleTable);
                loadSampleSourceInfo(newCurSampleTable, curDataId);
                setTimeout(() => {
                  setDevOptions(devGridSampleTableRef, { focusedRowIndex: index });
                }, 500);
              }
            },
          });
        }
      }, 10);
    }
  };

  function leftContainer() {
    function tableTitleRender(e: any): ReactNode {
      const sampleTable: SampleTable = e.data;
      let html = e.text;
      //如果没有设置文本字段,报警告
      if (sampleTable.sampleTextFieldsArray.length == 0) {
        html = (
          <span>
            <QuestionCircleTwoTone
              onClick={() => {
                msgError('没有选择抽样项目字段');
              }}
              title="没有选择抽样项目字段"
              style={{ marginLeft: -2, marginRight: 5 }}
              twoToneColor="red"
            />
            {html}
          </span>
        );
      }
      return html;
    }

    /**
     * 抽样表表
     */
    const sampleTableColumns: IColumnProps[] = [
      {
        dataField: 'rn',
        caption: consts.xh,
        alignment: 'center',
        width: 45,
        allowFiltering: false,
        allowEditing: false,
      },
      {
        dataField: 'tableTitle',
        caption: '抽样表名',
        alignment: 'left',
        allowFiltering: true,
        allowEditing: true,
        cellRender: tableTitleRender,
      },
    ];
    return (
      <div id="leftContainer" style={{ marginRight: '15px', height: '100%' }}>
        <div
          className="itemBoxDispalyLeft"
          style={{ marginLeft: 5, alignItems: 'center', marginBottom: 5 }}
        >
          <div>账套：</div>
          <SelectBox
            style={{ zIndex: 1 }}
            width={185}
            dataSource={accountInfoList}
            displayExpr="displayName"
            valueExpr="Data_ID"
            value={curDataId}
            dropDownOptions={{ width: 300 }}
            onValueChange={(e: any) => {
              setCurDataId(e);
              loadSampleTableList(e);

              //loadSampleSourceDataList(0, pageSize, curSampleTable, sampleSourceFields, e)
            }}
          />
        </div>
        <DevGrid.MultipleCheckBox
          className={` PaperDevSortableGrid devHeadersCenter`}
          height={'100%'}
          width="100%"
          ref={devGridSampleTableRef}
          dataSource={sampleTableList}
          keyExpr="guid"
          defaultColumns={sampleTableColumns}
          showBorders={true}
          isRemote={true}
          showRowLines={false}
          showColumnLines={true}
          allowColumnResizing={true}
          paging={{ enabled: false }}
          loadPanel={{ enabled: true, showPane: true }}
          columnMinWidth={30}
          focusedRowEnabled={true}
          defaultFocusedRowIndex={0}
          columnAutoWidth={true}
          onRowClick={(e: any) => {
            setCurSampleTable(e.data);
            loadSampleSourceInfo(e.data, curDataId);
          }}
          headerFilter={{ texts: { ok: '确定' } }}
          onEditingStart={(e: EditingStartEvent) => {
            e.cancel = !e.data?.isCustom;
            if (e.cancel) {
              //msgError('系统定义的表名,不能编辑!');
            }
          }}
          onRowUpdated={(e: any) => {
            udpateSampleTableValue(
              sampleTableList,
              curSampleTable as SampleTable,
              dbname,
              'tableTitle',
              e.data.tableTitle,
            );
          }}
          editing={{
            mode: 'batch',
            allowUpdating: false,
            allowDeleting: false,
            texts: { editRow: '修名称' },
            useIcons: true,
            startEditAction: 'dblClick',
          }}
          disableFirstHeaderSearch={true}
        >
          {useMemo(() => {
            return (
              <Toolbar>
                <Item location="before">
                  <Button
                    type="default"
                    icon="import"
                    text="导入Excel表"
                    onClick={() => showImportExcelPopup()}
                  ></Button>
                </Item>
                <Item location="before">
                  <Button
                    icon="iconfont icon-rename-copy"
                    className="editButton_Style"
                    hint="重命名"
                    onClick={onEditClickOfTable}
                  />
                </Item>

                <Item location="before">
                  <Button
                    icon="iconfont icon-del"
                    className="delButton_Style"
                    hint="删除"
                    onClick={onDelClickOfTable}
                  />
                </Item>
                <Item location="before">
                  <Button
                    icon="iconfont icon-refresh"
                    className="refreshButton_Style"
                    hint="刷新"
                    onClick={() => {
                      loadSampleTableList(curDataId);
                      //  getSampleTableList(dbname, setSampleTableList)
                    }}
                  />
                </Item>
              </Toolbar>
            );
          }, [curSampleTable, sampleTableList])}
        </DevGrid.MultipleCheckBox>
      </div>
    );
  }

  function rightContainer() {
    return (
      <div id="rightContainer" style={{ marginLeft: 10, marginRight: '15px', height: '100%' }}>
        {useMemo(() => {
          return (
            <DevGrid.RangeTap
              className={` PaperDevSortableGrid devHeadersCenter`}
              height={'90%'}
              width="100%"
              id="devGriSampleSource"
              ref={devGridSampleSourceRef}
              dataSource={sampleSourceTableDataSource}
              keyExpr="rn"
              columns={sampleSourceDataColumns} //不加这个,setSampleSourceDataColumns会导致这个报错
              showBorders={true}
              showRowLines={true}
              showColumnLines={true}
              isRemote={true}
              allowColumnResizing={true}
              columnMinWidth={30}
              defaultFocusedRowIndex={0}
              searchPanel={{ visible: false, width: 100 }}
              headerFilter={{ visible: true, allowSearch: true, texts: { ok: '确定' } }}
              pager={getGridDefaultPageProps()}
              //focusedRowEnabled={true} 这个属性不能加,会导致数组分页的totalCount不生效
              remoteOperations={{ paging: true, sorting: true, filtering: true }} //加这个才能支持远程分页 本地过滤 20230507
              sorting={{ mode: 'multiple' }} //shift多排序
              renderAsync={true}
              loadPanel={{ enabled: true, shading: true,shadingColor: 'rgba(0,0,0,0.3)'  }}
              sheetName={curSampleTable?.tableTitle}
              excelName={curSampleTable?.tableTitle + '-' + formatDateYYMMDD(new Date())}
              loadAllDevGridExport={async () => {
                //全部导出时的数据源
                setLoading(true);
                console.time('loadAllDevGridExport');
                const rowsData = !curSampleTable
                  ? []
                  : await loadSampleSourceDataListOnly(
                      dbname,
                      curSampleTable,
                      0,
                      consts.maxExportCount,
                      sampleSourceFields,
                      '',
                      curDataId,
                    );

                udpateRowsDataRnValue(rowsData, 0, consts.maxExportCount, sampleSourceFields);

                console.timeEnd('loadAllDevGridExport');
                setLoading(false);
                return { dataSource: rowsData };
              }}
              onCellClick={(e) => {
                const field = sampleSourceFields.find(
                  (item) => item.fieldName === e.column.dataField,
                );
                if (field) {
                  if (
                    !field.displayFormat &&
                    e.column.format &&
                    typeof e.column.format == 'string'
                  ) {
                    field.displayFormat = e.column.format;
                  }
                  setCurSampleSourceField({ ...field });
                }
              }}
              onRowDblClick={(e) => {
                if (curSampleTable?.isVoucher) {
                  //双击打开 凭证
                  setIsNeedAccountingVouche(true);
                  const interval = setInterval(() => {
                    if (accountingVoucherPupopRef?.current) {
                      clearInterval(interval);
                      accountingVoucherPupopRef.current.showPupop(
                        {
                          ...e.data,
                          Data_ID: sjnd,
                          dbname,
                          // cancelCallback: () => setIsNeedAccountingVouche(false)
                        },
                        [],
                      );
                    }
                  }, 10);
                }
              }}
            >
              <Paging
                enabled={true}
                defaultPageSize={consts.defaultSampePageSize}
                /*  pageIndex={pageIndex}
                     pageSize={pageSize}


                     onPageIndexChange={(pageIndex: number) => {
                         setPageIndex(pageIndex)
                         loadSampleSourceDataList(pageIndex, pageSize, curSampleTable, sampleSourceFields, curDataId);
                     }}
                     onPageSizeChange={(pageSize: number) => {
                         setPageSize(pageSize);
                         setPageIndex(0);//修改后要pageIndex设置第1页
                         loadSampleSourceDataList(0, pageSize, curSampleTable, sampleSourceFields, curDataId);
                     }} */
              />

              <Toolbar>
                {/*  <Item location='before' locateInMenu={'auto'} key="accountInfoList">
                            <div style={{ marginLeft: 10, display: curSampleTable?.isCustom ? 'none' : 'flex', alignItems: 'center' }} >
                                <div>账套：</div>
                                <SelectBox
                                    style={{ zIndex: 1 }}
                                    width={200}
                                    dataSource={accountInfoList}
                                    displayExpr='displayName'
                                    valueExpr='Data_ID'
                                    value={curDataId}

                                    dropDownOptions={{ width: 300 }}

                                    onValueChanged={(e: any) => {
                                        setCurDataId(e.value)
                                        setPageIndex(0);//切换样本时,要回到第1页
                                        loadSampleSourceDataList(0, pageSize, curSampleTable, sampleSourceFields, e.value)
                                    }}
                                />
                            </div>
                        </Item> */}
                <Item location="after" key="sampleTextFields">
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div>抽样项目字段：</div>

                    <TagBox
                      width={150}
                      placeholder="请选择字段"
                      searchEnabled={true}
                      multiline={false}
                      valueExpr="fieldName"
                      displayExpr="fieldTitle"
                      items={sampleSourceFields}
                      value={curSampleTable?.sampleTextFieldsArray}
                      showSelectionControls={true}
                      applyValueMode="useButtons"
                      onValueChanged={async (e: any) => {
                        if (curSampleTable) {
                          // 获取抽样项目字段值是否唯一
                          if (
                            e.value.length &&
                            !(await getTextFieldValueIsKeyOfMsg(
                              dbname,
                              curSampleTable,
                              e.value,
                              curDataId,
                            ))
                          ) {
                            return;
                          }

                          setCurSampleTable({ ...curSampleTable, sampleTextFieldsArray: e.value });
                          updateSampleTableProps(
                            sampleTableList,
                            curSampleTable,
                            'sampleTextFieldsArray',
                            e.value,
                          );

                          udpateSampleTableValue(
                            sampleTableList,
                            curSampleTable,
                            dbname,
                            'sampleTextFields',
                            e.value.join(','),
                          );
                        }
                      }}
                      maxDisplayedTags={1} //显示为第一项+等几项
                      onMultiTagPreparing={(args: any) =>
                        tabBoxOnMultiTagPreparingOfProp(args, 'fieldTitle')
                      }
                      dropDownOptions={{ minWidth: 300, width: 400 }}
                    />
                  </div>
                </Item>
                <Item location="after" key="sampleNumFields">
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div>抽样金额字段：</div>
                    <TagBox
                      width={150}
                      placeholder="请选择字段"
                      searchEnabled={true}
                      multiline={false}
                      valueExpr="fieldName"
                      displayExpr="fieldTitle"
                      items={sampleSourceFields?.filter((item) => item.isNum)}
                      value={curSampleTable?.sampleNumFieldsArray}
                      showSelectionControls={true}
                      applyValueMode="useButtons"
                      onValueChanged={(e: any) => {
                        if (curSampleTable) {
                          let values: string[] = e.value;
                          if (curSampleTable.isCustom && values.length > 1) {
                            values = [values[0]]; //只保留一个
                            msgError('自定义表只能选择一个金额字段');
                          }
                          setCurSampleTable({ ...curSampleTable, sampleNumFieldsArray: values });
                          updateSampleTableProps(
                            sampleTableList,
                            curSampleTable,
                            'sampleNumFieldsArray',
                            values,
                          );
                          udpateSampleTableValue(
                            sampleTableList,
                            curSampleTable,
                            dbname,
                            'sampleNumFields',
                            values.join(','),
                          );
                        }
                      }}
                      maxDisplayedTags={1} //显示为第一项+等几项
                      onMultiTagPreparing={(args: any) =>
                        tabBoxOnMultiTagPreparingOfProp(args, 'fieldTitle')
                      }
                      dropDownOptions={{ minWidth: 300, width: 400 }}
                    />
                  </div>
                </Item>
                <Item location="after">
                  <Button
                    style={{ padding: 0 }}
                    text="排序字段"
                    onClick={() => showSortFieldsPopup(curSampleTable)}
                  ></Button>
                </Item>
                <Item location="after" key="searchPanel" name="searchPanel" />
                <Item location="after" key="refresh">
                  <Button
                    icon="iconfont icon-refresh"
                    className="refreshButton_Style"
                    onClick={() =>
                      loadSampleSourceDataList(curSampleTable, sampleSourceFields, curDataId)
                    }
                  />
                </Item>
              </Toolbar>
            </DevGrid.RangeTap>
          );
        }, [curSampleTable, sampleSourceFields, accountInfoList, sampleSourceTableDataSource])}
        {useMemo(() => {
          return (
            <div style={{ height: '10%', minHeight: 30, borderTop: '1px solid #e5e5e5' }}>
              <div className="itemBoxDispalyLeft" style={{ marginTop: 10 }}>
                <div style={{ marginTop: 5, marginLeft: 5 }}>字段名称：</div>
                <SelectBox
                  width={200}
                  dataSource={sampleSourceFields}
                  displayExpr="fieldTitle"
                  valueExpr="fieldName"
                  value={curSampleSourceField?.fieldName}
                  dropDownOptions={{ width: 300 }}
                  onValueChange={(value: any) => {
                    //下拉触发
                    const field = sampleSourceFields.find((item) => item.fieldName == value);
                    setCurSampleSourceField(field);
                  }}
                  onValueChanged={(e: any) => {
                    //这个事件,其他地址修改也会触发
                  }}
                />
                <div style={{ marginTop: 5, marginLeft: 5 }}>字段类型：</div>
                <SelectBox
                  width={100}
                  dataSource={consts.isNumFieldsList}
                  displayExpr="text"
                  valueExpr="id"
                  disabled={curSampleTable?.isVoucher}
                  value={curSampleSourceField?.isNum}
                  //dropDownOptions={{ width: 300 }}
                  onValueChange={(value: any) => {
                    if (curSampleSourceField) {
                      if (
                        value &&
                        !getFieldValuesIsNumber(
                          devGridSampleSourceRef,
                          curSampleSourceField.fieldName,
                        )
                      ) {
                        msgError(
                          '请检查数据,字段【' + curSampleSourceField.fieldTitle + '】存在非数数字!',
                        );
                        return;
                      }
                      curSampleSourceField.isNum = value;
                      curSampleSourceField.displayFormat = value ? consts.numberFormat2Bit : '';

                      setCurSampleSourceField({ ...curSampleSourceField });
                    }
                  }}
                />
                <div style={{ marginTop: 5, marginLeft: 5 }}>显示格式：</div>
                <SelectBox
                  width={100}
                  disabled={curSampleTable?.isVoucher}
                  dataSource={consts.displayFormatList}
                  displayExpr="text"
                  valueExpr="id"
                  value={curSampleSourceField?.displayFormat || ''}
                  onValueChange={(value: any) => {
                    //onValueChanged其他改后,也会执行里
                    if (curSampleSourceField) {
                      curSampleSourceField.displayFormat = value;
                      curSampleSourceField.align = value.includes(consts.numberFormat0)
                        ? 'right'
                        : 'left';
                      setCurSampleSourceField({ ...curSampleSourceField });
                    }
                  }}
                />
                <Button
                  disabled={curSampleTable?.isVoucher}
                  style={{ marginLeft: 5 }}
                  icon="save"
                  text="保存"
                  onClick={async () => {
                    if (curSampleTable && curSampleSourceField) {
                      const field = sampleSourceFields.find(
                        (item) => item.fieldName == curSampleSourceField.fieldName,
                      );
                      if (field) {
                        field.isNum = curSampleSourceField.isNum;
                        field.displayFormat = curSampleSourceField.displayFormat;
                        const displayFormat = consts.displayFormatList.find(
                          (item) => item.id == curSampleSourceField.displayFormat,
                        );
                        curSampleSourceField.align = (displayFormat?.id + '').includes(
                          consts.numberFormat0,
                        )
                          ? 'right'
                          : 'left';
                        field.align = curSampleSourceField.align;
                        setCurSampleSourceField({ ...curSampleSourceField });
                        let alterTableField = false;

                        if (displayFormat) {
                          if (field.isNum == 1) {
                            if (displayFormat.id) {
                              //不是空的(不是第1个)
                              alterTableField = await alterTableFieldType(
                                dbname,
                                curSampleTable.tableName,
                                field.fieldName,
                                displayFormat.sqlType,
                              );
                            }
                          } else {
                            //文本
                            const displayFormat = consts.displayFormatList.find(
                              (item) => item.id == '',
                            );
                            const length =
                              (await getTableFieldValueMaxLen(
                                dbname,
                                curSampleTable.tableName,
                                field.fieldName,
                              )) + 20;
                            const sqlType = displayFormat?.sqlType.replaceAll(
                              '{length}',
                              `${length}`,
                            );
                            alterTableField = await alterTableFieldType(
                              dbname,
                              curSampleTable.tableName,
                              field.fieldName,
                              sqlType,
                            );
                          }
                        }
                        if (alterTableField) {
                          await udpateSampleTableFieldInfo(dbname, curSampleSourceField);
                          loadSampleSourceInfo(curSampleTable, curDataId);
                          msgInfo('保存字段信息成功');
                        }
                      }
                    } else {
                      msgError('还没有选择字段,请选择字段!');
                    }
                  }}
                />

                <div
                  style={{
                    marginTop: 8,
                    marginLeft: 5,
                    color: 'red',
                    display: curSampleTable?.isVoucher ? '' : 'none',
                  }}
                >
                  注:凭证表不可修改
                </div>
              </div>
            </div>
          );
        }, [curSampleTable, sampleSourceFields, curSampleSourceField])}
      </div>
    );
  }

  return (
    <>
      {isNeedSortFieldsPopup && <SortFieldsPopup ref={sortFieldsPopupRef} />}
      {isNeedImportExcelPopup && <ImportExcelPupop ref={importExcelPopupRef} />}

      {isNeedAccountingVouche && (
        <AccountingVoucherPupop
          ref={accountingVoucherPupopRef}
          cellDblClickCallback={(rowData: any, curYear: any) => {
            msgInfo(`正在打开 明细账, 请稍候...`);
            if (window.electronComponents) {
              const sessionParams = JSON.parse(window.sessionStorage.electronParams);
              const { sjxmbh, ZcbfID } = sessionParams.params;
              window.location.href = `cpas://OpenLocalFile/?fileName={UFCPAS4_PATH}/UFCPAS4.exe&params=UserCode={UserCode} UserPwd={UserPwd} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID} Functions=FM_103 FunParameters="Data_ID=${curYear},KMBH=${rowData.KMBH}"`;
            } else {
              console.error('window["electronComponents"] false');
            }
          }}
        />
      )}
      <Popup
        ref={popupRef}
        disabled={loading}
        visible={visible}
        title={'样本源维护 ' + (curSampleTable?.tableTitle || '')}
        width={'98vw'}
        height={'98vh'}
        onTitleRendered={(e) => {
          devPopupTitleRendered(e, '500px');
        }} //解决 dx-popup 标题有....的问题
        onHiding={() => {
          onCancel();
        }}
        // disabled={loading}
      >
        <div style={{ height: '100%', width: '100%', overflow: 'hidden' }}>
          <LayoutB
            rowSize={['260px', '260px']}
            leftSlot={leftContainer()}
            rightSlot={rightContainer()}
          />
        </div>
        <LoadPanel visible={loading} />
      </Popup>
    </>
  );
});
